package com.example.handheld4_gsignal_app.ui.activities;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.handheld4_gsignal_app.R;
import com.example.handheld4_gsignal_app.data.SignalRecord;
import com.example.handheld4_gsignal_app.services.HistoryService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图表展示Activity - 显示信号数据的各种图表
 */
public class ChartActivity extends AppCompatActivity {
    
    private HistoryService historyService;
    private List<SignalRecord> signalRecords;
    
    private LineChart lineChart;
    private BarChart barChart;
    private Button btnSignalChart;
    private Button btnNetworkChart;
    private Button btnOperatorChart;
    private TextView tvChartTitle;
    private TextView tvDataCount;
    private LinearLayout chartContainer;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);
        
        initViews();
        initServices();
        setupClickListeners();
        loadData();
        showSignalStrengthChart();
    }
    
    /**
     * 初始化视图组件
     */
    private void initViews() {
        lineChart = findViewById(R.id.line_chart);
        barChart = findViewById(R.id.bar_chart);
        btnSignalChart = findViewById(R.id.btn_signal_chart);
        btnNetworkChart = findViewById(R.id.btn_network_chart);
        btnOperatorChart = findViewById(R.id.btn_operator_chart);
        tvChartTitle = findViewById(R.id.tv_chart_title);
        tvDataCount = findViewById(R.id.tv_data_count);
        chartContainer = findViewById(R.id.chart_container);
    }
    
    /**
     * 初始化服务
     */
    private void initServices() {
        historyService = new HistoryService(this);
    }
    
    /**
     * 设置点击监听器
     */
    private void setupClickListeners() {
        btnSignalChart.setOnClickListener(v -> showSignalStrengthChart());
        btnNetworkChart.setOnClickListener(v -> showNetworkTypeChart());
        btnOperatorChart.setOnClickListener(v -> showOperatorChart());
    }
    
    /**
     * 加载数据
     */
    private void loadData() {
        // 检查是否使用传递的数据
        boolean usePassedData = getIntent().getBooleanExtra("use_passed_data", false);
        
        if (usePassedData) {
            // 使用从HistoryFragment传递的数据
            loadPassedData();
        } else {
            // 检查是否使用过滤数据（兼容旧版本）
            boolean useFilteredData = getIntent().getBooleanExtra("use_filtered_data", false);
            String filterType = getIntent().getStringExtra("filter_type");
            
            if (useFilteredData && filterType != null) {
                // 使用与HistoryFragment相同的过滤逻辑
                loadFilteredData(filterType);
            } else {
                // 默认从服务器获取所有真实数据
                loadAllDataFromServer();
            }
        }
    }
    
    /**
     * 加载从HistoryFragment传递的数据
     */
    private void loadPassedData() {
        try {
            String jsonData = getIntent().getStringExtra("signal_data");
            if (jsonData != null && !jsonData.isEmpty()) {
                // 解析JSON数据
                Gson gson = new Gson();
                Type listType = new TypeToken<List<SignalRecord>>(){}.getType();
                signalRecords = gson.fromJson(jsonData, listType);
                
                // 显示默认图表
                showSignalStrengthChart();
            } else {
                // 如果没有传递数据，显示错误信息
                showNoDataMessage();
            }
        } catch (Exception e) {
            // 解析失败，显示错误信息
            showNoDataMessage();
        }
    }
    
    /**
     * 显示无数据消息
     */
    private void showNoDataMessage() {
        tvChartTitle.setText("无数据可显示");
        tvDataCount.setText("数据条数: 0");
        // 隐藏图表
        lineChart.setVisibility(View.GONE);
        barChart.setVisibility(View.GONE);
    }
    
    /**
     * 从服务器加载所有数据
     */
    private void loadAllDataFromServer() {
        // 从服务器获取所有数据
        String deviceId = "DEVICE_001";
        int limit = 100;
        int offset = 0;
        
        historyService.fetchHistoryDataFromServer(deviceId, null, null, limit, offset,
                new HistoryService.HistoryCallback() {
            @Override
            public void onSuccess(List<SignalRecord> records) {
                runOnUiThread(() -> {
                    signalRecords = records;
                    // 显示默认图表
                    showSignalStrengthChart();
                });
            }
            
            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    // 如果服务器查询失败，显示无数据消息
                    showNoDataMessage();
                });
            }
        });
    }
    
    /**
     * 加载过滤后的数据
     */
    private void loadFilteredData(String filterType) {
        String startTime = null;
        String endTime = null;
        
        switch (filterType) {
            case "今天":
                startTime = getTodayStartTime();
                endTime = getTodayEndTime();
                break;
            case "本周":
                startTime = getWeekStartTime();
                endTime = getWeekEndTime();
                break;
            case "本月":
                startTime = getMonthStartTime();
                endTime = getMonthEndTime();
                break;
            default:
                // 全部数据，不设置时间限制
                signalRecords = historyService.getAllRecords();
                return;
        }
        
        // 从服务器获取过滤后的数据
        String deviceId = "DEVICE_001";
        int limit = 100;
        int offset = 0;
        
        historyService.fetchHistoryDataFromServer(deviceId, startTime, endTime, limit, offset,
                new HistoryService.HistoryCallback() {
            @Override
            public void onSuccess(List<SignalRecord> records) {
                runOnUiThread(() -> {
                    signalRecords = records;
                    // 重新显示当前图表
                    if (btnSignalChart.isSelected()) {
                        showSignalStrengthChart();
                    } else if (btnNetworkChart.isSelected()) {
                        showNetworkTypeChart();
                    } else if (btnOperatorChart.isSelected()) {
                        showOperatorChart();
                    } else {
                        showSignalStrengthChart();
                    }
                });
            }
            
            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    // 如果服务器查询失败，使用本地数据
                    switch (filterType) {
                        case "今天":
                            signalRecords = historyService.getTodayRecords();
                            break;
                        case "本周":
                            signalRecords = historyService.getWeekRecords();
                            break;
                        case "本月":
                            signalRecords = historyService.getMonthRecords();
                            break;
                        default:
                            signalRecords = historyService.getAllRecords();
                            break;
                    }
                    // 重新显示当前图表
                    if (btnSignalChart.isSelected()) {
                        showSignalStrengthChart();
                    } else if (btnNetworkChart.isSelected()) {
                        showNetworkTypeChart();
                    } else if (btnOperatorChart.isSelected()) {
                        showOperatorChart();
                    } else {
                        showSignalStrengthChart();
                    }
                });
            }
        });
    }
    
    /**
     * 显示信号强度折线图 - 按设备分组
     */
    private void showSignalStrengthChart() {
        String filterType = getIntent().getStringExtra("filter_type");
        String title = "📶 信号强度趋势图 (按设备)";
        if (filterType != null && !filterType.equals("全部")) {
            title += " - " + filterType;
        }
        tvChartTitle.setText(title);
        
        // 隐藏柱状图，显示折线图
        barChart.setVisibility(View.GONE);
        lineChart.setVisibility(View.VISIBLE);
        
        if (signalRecords == null || signalRecords.isEmpty()) {
            return;
        }
        
        // 按设备ID分组数据
        Map<String, List<SignalRecord>> deviceGroups = signalRecords.stream()
            .collect(Collectors.groupingBy(
                record -> record.getDeviceId() != null ? record.getDeviceId() : "未知设备"
            ));
        
        // 准备数据
        List<ILineDataSet> dataSets = new ArrayList<>();
        List<String> labels = new ArrayList<>();
        
        // 定义不同设备的颜色
        int[] colors = {
            Color.parseColor("#00E5FF"), // 蓝色
            Color.parseColor("#00E676"), // 绿色
            Color.parseColor("#FFD600"), // 黄色
            Color.parseColor("#FF1744"), // 红色
            Color.parseColor("#9C27B0"), // 紫色
            Color.parseColor("#FF9800")  // 橙色
        };
        
        int colorIndex = 0;
        for (Map.Entry<String, List<SignalRecord>> entry : deviceGroups.entrySet()) {
            String deviceId = entry.getKey();
            List<SignalRecord> deviceRecords = entry.getValue();
            
            // 按时间排序
            deviceRecords.sort((r1, r2) -> r1.getCollectedAt().compareTo(r2.getCollectedAt()));
            
            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < deviceRecords.size(); i++) {
                SignalRecord record = deviceRecords.get(i);
                entries.add(new Entry(i, record.getSignalStrength()));
                
                // 只在第一次循环时添加时间标签
                if (colorIndex == 0) {
                    labels.add(record.getCollectedAt().substring(11, 16)); // 只显示时间部分
                }
            }
            
            // 创建数据集
            LineDataSet dataSet = new LineDataSet(entries, deviceId);
            dataSet.setColor(colors[colorIndex % colors.length]);
            dataSet.setLineWidth(3f);
            dataSet.setCircleColor(colors[colorIndex % colors.length]);
            dataSet.setCircleRadius(6f); // 增大圆圈半径，让数据点更明显
            dataSet.setValueTextColor(Color.parseColor("#E8F4FD"));
            dataSet.setValueTextSize(12f); // 增大文字大小
            dataSet.setDrawFilled(false); // 多条线时不填充
            dataSet.setDrawValues(true); // 显示数值
            dataSet.setDrawCircles(true); // 显示圆圈
            dataSet.setCircleHoleColor(colors[colorIndex % colors.length]); // 圆圈内部颜色
            dataSet.setCircleHoleRadius(3f); // 圆圈内部半径
            
            // 设置数值格式化器，显示更清晰的信号强度值
            dataSet.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return String.format("%.1f dBm", value);
                }
            });
            
            dataSets.add(dataSet);
            colorIndex++;
        }
        
        // 创建数据
        LineData lineData = new LineData(dataSets);
        lineChart.setData(lineData);
        
        // 配置图表
        setupLineChart();
        
        // 更新数据统计
        updateDataCount();
    }
    
    /**
     * 显示网络类型柱状图
     */
    private void showNetworkTypeChart() {
        String filterType = getIntent().getStringExtra("filter_type");
        String title = "📡 网络类型分布图";
        if (filterType != null && !filterType.equals("全部")) {
            title += " - " + filterType;
        }
        tvChartTitle.setText(title);
        
        // 隐藏折线图，显示柱状图
        lineChart.setVisibility(View.GONE);
        barChart.setVisibility(View.VISIBLE);
        
        if (signalRecords == null || signalRecords.isEmpty()) {
            return;
        }
        
        // 统计网络类型
        Map<String, Long> networkTypes = signalRecords.stream()
            .collect(Collectors.groupingBy(
                record -> record.getNetworkType() != null ? record.getNetworkType() : "未知",
                Collectors.counting()
            ));
        
        // 准备数据
        List<BarEntry> entries = new ArrayList<>();
        List<String> labels = new ArrayList<>();
        
        int index = 0;
        for (Map.Entry<String, Long> entry : networkTypes.entrySet()) {
            entries.add(new BarEntry(index, entry.getValue()));
            labels.add(entry.getKey());
            index++;
        }
        
        // 创建数据集
        BarDataSet dataSet = new BarDataSet(entries, "记录数量");
        dataSet.setColors(new int[]{
            Color.parseColor("#00E5FF"),
            Color.parseColor("#00E676"),
            Color.parseColor("#FFD600"),
            Color.parseColor("#FF1744")
        });
        dataSet.setValueTextColor(Color.parseColor("#E8F4FD"));
        dataSet.setValueTextSize(12f);
        
        // 创建数据
        BarData barData = new BarData(dataSet);
        barChart.setData(barData);
        
        // 配置图表
        setupBarChart(labels);
        
        // 更新数据统计
        updateDataCount();
    }
    
    /**
     * 显示运营商柱状图
     */
    private void showOperatorChart() {
        String filterType = getIntent().getStringExtra("filter_type");
        String title = "🏢 运营商分布图";
        if (filterType != null && !filterType.equals("全部")) {
            title += " - " + filterType;
        }
        tvChartTitle.setText(title);
        
        // 隐藏折线图，显示柱状图
        lineChart.setVisibility(View.GONE);
        barChart.setVisibility(View.VISIBLE);
        
        if (signalRecords == null || signalRecords.isEmpty()) {
            return;
        }
        
        // 统计运营商
        Map<String, Long> operators = signalRecords.stream()
            .collect(Collectors.groupingBy(
                record -> {
                    String operatorName = record.getOperatorName();
                    if (operatorName == null || operatorName.isEmpty()) {
                        return "未知";
                    }
                    // 修复字符编码问题
//                    try {
//                        // 重新编码确保中文字符正确显示
//                        byte[] bytes = operatorName.getBytes("ISO-8859-1");
//                        return new String(bytes, "UTF-8");
//                    } catch (Exception e) {
//                        // 如果编码转换失败，返回原始字符串
//                        return operatorName;
//                    }
                    return operatorName;
                },
                Collectors.counting()
            ));
        
        // 准备数据
        List<BarEntry> entries = new ArrayList<>();
        List<String> labels = new ArrayList<>();
        
        int index = 0;
        for (Map.Entry<String, Long> entry : operators.entrySet()) {
            entries.add(new BarEntry(index, entry.getValue()));
            labels.add(entry.getKey());
            index++;
        }
        
        // 创建数据集
        BarDataSet dataSet = new BarDataSet(entries, "记录数量");
        dataSet.setColors(new int[]{
            Color.parseColor("#00E5FF"),
            Color.parseColor("#00E676"),
            Color.parseColor("#FFD600"),
            Color.parseColor("#FF1744")
        });
        dataSet.setValueTextColor(Color.parseColor("#E8F4FD"));
        dataSet.setValueTextSize(12f);
        
        // 创建数据
        BarData barData = new BarData(dataSet);
        barChart.setData(barData);
        
        // 配置图表
        setupBarChart(labels);
        
        // 更新数据统计
        updateDataCount();
    }
    
    /**
     * 更新数据统计显示
     */
    private void updateDataCount() {
        if (signalRecords != null && tvDataCount != null) {
            tvDataCount.setText("数据条数: " + signalRecords.size());
        }
    }
    
    /**
     * 配置折线图
     */
    private void setupLineChart() {
        // 设置背景
        lineChart.setBackgroundColor(Color.parseColor("#1A1F2E"));
        
        // 配置X轴
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.parseColor("#B0BEC5"));
        xAxis.setGridColor(Color.parseColor("#37474F"));
        xAxis.setAxisLineColor(Color.parseColor("#37474F"));
        
        // 配置Y轴
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setTextColor(Color.parseColor("#B0BEC5"));
        leftAxis.setGridColor(Color.parseColor("#37474F"));
        leftAxis.setAxisLineColor(Color.parseColor("#37474F"));
        
        // 设置Y轴范围，确保信号强度变化更明显
        if (signalRecords != null && !signalRecords.isEmpty()) {
            double minSignal = signalRecords.stream().mapToDouble(SignalRecord::getSignalStrength).min().orElse(-110);
            double maxSignal = signalRecords.stream().mapToDouble(SignalRecord::getSignalStrength).max().orElse(-70);
            
            // 添加一些边距，让图表更美观
            double range = maxSignal - minSignal;
            double margin = Math.max(range * 0.1, 2.0); // 至少2dBm的边距
            
            leftAxis.setAxisMinimum((float)(minSignal - margin));
            leftAxis.setAxisMaximum((float)(maxSignal + margin));
            leftAxis.setGranularity(2.0f); // 设置刻度间隔为2dBm
        }
        
        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setEnabled(false);
        
        // 配置图例
        lineChart.getLegend().setTextColor(Color.parseColor("#E8F4FD"));
        
        // 配置描述
        lineChart.getDescription().setEnabled(false);
        
        // 动画
        lineChart.animateX(1000);
        
        // 刷新图表
        lineChart.invalidate();
    }
    
    /**
     * 配置柱状图
     */
    private void setupBarChart(List<String> labels) {
        // 设置背景
        barChart.setBackgroundColor(Color.parseColor("#1A1F2E"));
        
        // 配置X轴
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.parseColor("#B0BEC5"));
        xAxis.setGridColor(Color.parseColor("#37474F"));
        xAxis.setAxisLineColor(Color.parseColor("#37474F"));
        xAxis.setValueFormatter(new IndexAxisValueFormatter(labels));
        xAxis.setLabelCount(labels.size());
        
        // 配置Y轴
        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setTextColor(Color.parseColor("#B0BEC5"));
        leftAxis.setGridColor(Color.parseColor("#37474F"));
        leftAxis.setAxisLineColor(Color.parseColor("#37474F"));
        
        YAxis rightAxis = barChart.getAxisRight();
        rightAxis.setEnabled(false);
        
        // 配置图例
        barChart.getLegend().setTextColor(Color.parseColor("#E8F4FD"));
        
        // 配置描述
        barChart.getDescription().setEnabled(false);
        
        // 动画
        barChart.animateY(1000);
        
        // 刷新图表
        barChart.invalidate();
    }
    
    /**
     * 获取今天的开始时间 (ISO 8601格式)
     */
    private String getTodayStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取今天的结束时间 (ISO 8601格式)
     */
    private String getTodayEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取本周的开始时间 (ISO 8601格式)
     */
    private String getWeekStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取本周的结束时间 (ISO 8601格式)
     */
    private String getWeekEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取本月的开始时间 (ISO 8601格式)
     */
    private String getMonthStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取本月的结束时间 (ISO 8601格式)
     */
    private String getMonthEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        return sdf.format(calendar.getTime());
    }
}